<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MBdzxLog;
use App\Models\MConsumeLog;
use App\Models\MLog;
use App\Models\MUser;
use App\Models\MUserAttr;

use App\Models\MWallet;

use App\Models\MVip_award;
use App\Models\MVip_up_log;

use App\Templates\ActivationUserAct;
use App\Templates\RegUserAct;
use App\Utils\TreeUtil;
use App\VModels\VVip;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 会员管理控制器
 */
class UserController extends Controller
{
    use RegUserAct, ActivationUserAct;

    /**
     * 会员列表
     * $flag 1=全部会员列表 2=未激活会员列表 3=已冻结会员列表 4=已禁用会员列表 5=内部会员列表 6=全部的报单中心
     * 7=报单中心申请中的处理
     */
    public function usersPage(Request $request, $flag, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.users', ['flag' => $flag]), 20, $request->getQueryString());
        $query = (new MUser())->query();

        //按指定菜单设置条件
        if ($flag == 2) {
            $query = $query->where('ok_status', MUser::$STATUS_NOACTIVATED);

        } elseif ($flag == 3) {
            $query = $query->where('status', MUser::$STATUS_FREEZE)
                ->orWhere('status', MUser::$STATUS_STOP_FREEZE);

        } elseif ($flag == 4) {
            $query = $query->where('status', MUser::$STATUS_STOP)
                ->orWhere('status', MUser::$STATUS_STOP_FREEZE);

        } elseif ($flag == 5) {
            $query = $query->where('in', MUser::$USER_IN);

        } elseif ($flag == 6) {
            $query = $query->where('bdzx_status', MUser::$BDZX_YES);

        } elseif ($flag == 7) {
            $query = $query->where('bdzx_status', MUser::$BDZX_APPLY);

        }

        //指定了 按时间段搜索
        if ($request->has(['time_type', 'start', 'end'])) {
            if ($request->time_type == 1) {//按注册时间段筛选
                $query = $query->where('reg_time', '>=', strtotime($request->start))
                    ->where('reg_time', '<=', strtotime($request->end));
            } elseif ($request->time_type == 2) {//按激活时间段筛选
                $query = $query->where('ok_time', '>=', strtotime($request->start))
                    ->where('ok_time', '<=', strtotime($request->end));
            }
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按会员用户名搜索
                $query = $query->where('username', 'like', "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) { //按会员ID搜索
                $query = $query->where('id', $request->search_str);

            }
//            elseif ($request->search_type == 3) { //按真实姓名搜索
//                $query = $query->where('realname', 'like', "%" . $request->search_str . "%");
//
//            }
//            elseif ($request->search_type == 4) { //按会员手机号搜索
//                $query = $query->where('mobile', 'like', "%" . $request->search_str . "%");
//
//            }
            elseif ($request->search_type == 5) { //按报单中心账号搜索
                $bdzx = MUser::where('username', $request->search_str)->first();
                $query = $query->where('bdzx', empty($bdzx) ? 0 : $bdzx->id);

            } elseif ($request->search_type == 6) { //按报单中心ID搜索
                $query = $query->where('bdzx', $request->search_str);

            } elseif ($request->search_type == 7) { //按会员编号搜索
                $query = $query->where('no', $request->search_str);
            }
        }
//        dd($request->sory_type);
        //指定了排序规则
        if ($request->has(['sort_type'])) {
            if ($request->sort_type == 1) {         //[ 注册时间 ] 降序 ↓
                $query = $query->orderBy('reg_time', 'desc');
            } elseif ($request->sort_type == 2) {   //[ 注册时间 ] 升序 ↑
                $query = $query->orderBy('reg_time', 'asc');
            } elseif ($request->sort_type == 3) {   //[ 激活时间 ] 降序 ↓
                $query = $query->orderBy('ok_time', 'desc');
            } elseif ($request->sort_type == 4) {   //[ 激活时间 ] 升序 ↑
                $query = $query->orderBy('ok_time', 'asc');
            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['users'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->get();

        $this->data['flag'] = $flag;
        $this->fyViewInit($this->data);

        return view("admin.users")->with($this->data);
    }

    /**
     * 进入会员前台
     */
    public function goUser($id)
    {
        $user = MUser::find($id);
        if (!empty($user)) {
            $user->loginStatus(true);
            return redirect()->route('web.center');
        } else {
            return back()->with($this->makeJsCode(1, "会员不存在！"));
        }
    }

    /**
     * 会员编辑界面
     */
    public function usersEditPage($id = 0)
    {
        $this->data['users'] = MUser::find($id);
        return view('admin.users_edit')->with($this->data);
    }

    /**
     * 会员信息保存
     */
    public function usersSave(Request $request, $id = 0)
    {
        if (!$this->validateReq($request, MUser::editRulesWithMsg(0), MUser::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use ($request, $id) {
                $users = MUser::find($id);

                if ($users->editSave($request)) {
                    $this->data = $this->makeJsCode(0, "修改用户信息成功！");
                    MLog::log("修改了用户 $users->username 的信息!");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "修改用户信息失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "修改用户信息失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 内部会员注册界面
     */
    public function userRegPage(Request $request)
    {
        return view('admin.reg_user');
    }

    /**
     * 管理员激活会员
     */
    public function adminActiveUser(Request $request, $id)
    {
        $bool = false; //后台激活是否扣除报单币 true 扣除  false 不扣除(默认)
        $user = MUser::find($id);
        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "要激活的用户不存在！");
            return back()->with($this->data);
        }
        if ($user->ok_status == 1) {
            $this->data = $this->makeJsCode(1, "不可重复激活！");
            return back()->with($this->data);
        }

        $bdzx = $user->bdzxUser;
        if ($bool == true) {
            $bdzx_wallet = $bdzx->wallet;
            $zje = VVip::attrBySlug($user->vip_slug)[MUser::$ATTR_ACTIVE];//激活会员所需总金额
            if ($bdzx_wallet < $zje) {
                $this->data = $this->makeJsCode(1, "报单中心余额不足！");
                return back()->with($this->data);
            }
        }

        try {
            DB::transaction(function () use (&$user, &$bdzx, &$bool) {
                if ($user->activation($bdzx, $ok_type = 0, $bool)) {
                    $this->data = $this->makeJsCode(0, "激活成功！");
                    MLog::log("后台激活了用户 $user->username ( ID: $user->id ) !");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "激活失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "激活失败！");
        }

        return back()->with($this->data);
    }

    /**
     * 删除未激活会员(只有未激活会员可以删除)
     */
    public function userDel($id)
    {
        try {
            DB::transaction(function () use ($id) {
                $user = MUser::find($id);
                if ($user->ok_status == MUser::$STATUS_ACTIVATED) {
                    $this->data = $this->makeJsCode(1, "已激活用户不可删除！");
                    return;
                }
                //删除未激活用户，写入系统日志，删除用户钱包，删除用户业绩记录
                if ($user->delUser()) {
                    MLog::log("删除了未激活用户 $user->username ( ID: $id ) !");
                    $this->data = $this->makeJsCode(0, "删除成功！");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "删除失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "删除失败！");
        }

        return back()->with($this->data);
    }

    /**
     * 开通/取消报单中心
     */
    public function openBdzx($id)
    {
        try {
            DB::transaction(function () use ($id) {
                $user = MUser::find($id);
                if ($user->bdzx_status == MUser::$BDZX_APPLY) {//当报单中心状态已申请
                    $this->data = $this->makeJsCode(1, "用户已申请报单中心状态,请前往报单中心管理操作！");
                    return back()->with($this->data);
                }
                if ($user->openBdzx(false)) {
                    if ($user->bdzx_status == MUser::$BDZX_YES) {
                        MLog::log("开通了用户 $user->username ( ID: $id ) 的报单中心身份 !");
                    } elseif ($user->bdzx_status == MUser::$BDZX_NO) {
                        MLog::log("取消了用户 $user->username ( ID: $id ) 的报单中心身份 !");
                    }
                    $this->data = $this->makeJsCode(0, "操作成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollback();
            $this->data = $this->makeJsCode(1, "操作失败！");
        }
        return back()->with($this->data);
    }

    /**
     * 冻结/取消冻结用户
     */
    public function freezeUser($id, $status)
    {
        try {
            DB::transaction(function () use ($id, $status) {
                if (MUser::freezeUser($id, $status)) {
                    $this->data = $this->makeJsCode(0, "操作成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollback();
            $this->data = $this->makeJsCode(1, "操作失败！");
        }
        return back()->with($this->data);
    }

    /**
     * 禁用/取消禁用用户
     */
    public function stopUser($id, $status)
    {
        try {
            DB::transaction(function () use ($id, $status) {
                if (MUser::stopUser($id, $status)) {
                    $this->data = $this->makeJsCode(0, "操作成功！");
                } else {
                    DB::rollBack();

                }
            });
        } catch (Exception $e) {
            DB::rollback();
            $this->data = $this->makeJsCode(1, "操作失败！");
        }

        return back()->with($this->data);
    }

    /**
     * 升级指定会员界面
     */
    public function vipUpPage()
    {
        $this->data['vip_awards'] = MVip_award::all();
        //会员等级
        $vips = VVip::getVipList();
        $this->data['vips'] = empty($vips) ? [] : $vips;
        return view('admin.vip_up')->with($this->data);
    }

    /**
     * 升级指定会员操作
     */
    public function vipUpSave(Request $request)
    {
        //对会员进行再次验证
        if (!$request->has(['username', 'vip'])) {
            $this->data = $this->makeJsCode(1, "填写信息不完整");
            return response()->json($this->data);

        }

        //检查用户是否存在
        $user = MUser::where('username', $request->username)->first();

        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "请填写有效用户");
            return response()->json($this->data);
        }

        //用户原等级
        $pre_vip_slug = $user->vip_slug;  //原来的会员标识
        $new_vip_slug = $request->vip; //新的会员标识
        $pre_vip_point = VVip::attrBySlug($pre_vip_slug)[MUser::$ATTR_POINT];   //获取原来的会员权重
        $new_Vip_point = VVip::attrBySlug($new_vip_slug)[MUser::$ATTR_POINT];  //获取现在的会员权重
        $pre_vip_name = VVip::vipBySlug($pre_vip_slug)->name; //原来的会员名称
        $new_vip_name = VVip::vipBySlug($new_vip_slug)->name; //新的会员名称

        try {
            DB::transaction(function () use ($request, $pre_vip_point, $new_Vip_point, $pre_vip_name, $new_vip_name, $user) {
                if ($user->upVip($request->vip)) {

                    if ($new_Vip_point > $pre_vip_point) {
                        $this->data = $this->makeJsCode("0", "升级了会员 $user->username 的等级!");
                        MLog::log("管理员把会员 $user->username ( ID: $user->id ) 的等级由 $pre_vip_name 升级为 $new_vip_name !");

                    } elseif ($new_Vip_point < $pre_vip_point) {
                        $this->data = $this->makeJsCode("0", "降低了会员 $user->username 的等级!");
                        MLog::log("管理员把会员 $user->username ( ID: $user->id ) 的等级由 $pre_vip_name 降级为 $new_vip_name !");

                    } elseif ($new_Vip_point == $pre_vip_point) {
                        $this->data = $this->makeJsCode("0", "会员 $user->username 的等级 $pre_vip_name 未发生变化!");
                    }
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode("1", "升级用户失败");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode("1", "升级用户失败");
        }
        return response()->json($this->data);
    }

    /**
     * 会员系谱图界面
     *
     * $id = 0 根节点
     */
    public function nodeTreePage(Request $request, $id = 0)
    {
        $user = null;
        if ($id == 0) {
            $user = TreeUtil::getNTreeRoot();
        } else {
            $user = MUser::find($id);
        }

        //按条件筛选
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) { //会员名搜索(精确搜索)
                $user = MUser::where('username', $request->search_str)->first();
            } elseif ($request->search_type == 2) {  //ID搜索(精确搜索)
                $user = MUser::find($request->search_str);
            }
        }

        //用户不存在
        if (!$user) {
            $this->toast = $this->makeJsCode(1, "搜索的用户不存在");
            return back()->with($this->toast);
        }

        $this->data['user'] = $user;
        return view('admin.node_tree')->with($this->data);
    }

    /**
     * 会员树状图界面
     *
     * $id = 0 根节点
     */
    public function zTreePage()
    {
        $user = MUser::select(['id', 'username', 'pid'])->get();

        $this->data['user'] = $user;

        return view('admin.node_zTree')->with($this->data);
    }

    /** 用户信息列表
     * @return $this 用户信息列表界面
     */
    public function userInfo()
    {
        $this->data['attrs'] = MUserAttr::all();
        return view('admin.user_info')->with($this->data);
    }

    /** 返回会员信息编辑界面
     *  $id 属性id
     */
    public function userInfoEditPage($id = 0)
    {
        $this->data['attr'] = MUserAttr::find($id);
        return view('admin.info_edit')->with($this->data);
    }

    /** 会员信息属性保存
     * @param Request $request 提交值
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfoSave(Request $request, $id = 0)
    {
        if (!$this->validateReq($request, MUserAttr::editInfoRulesWithMsg(0), MUserAttr::editInfoRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $info = MUserAttr::find($id);
        $mark = $request->mark;
        if (empty($info)) {
            $info = new MUserAttr();
            $mark = "attr_" . onlyNo();
            if ($info->exitName($request->name)) {
                $this->data = $this->makeJsCode(1, "名称已经存在");
                return response()->json($this->data);
            }
        }
        if ($info->exitNameExcept($request->name, $id)) {
            $this->data = $this->makeJsCode(1, "名称已经存在");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use ($request, $info, $mark) {
                if ($info->attrSave($request, $mark)) {
                    $this->data = $this->makeJsCode(0, "会员属性编辑成功！");
                    MLog::log("编辑了会员属性为 $request->name 的信息");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "会员属性编辑失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "会员属性编辑失败！");
        }

        return response()->json($this->data);
    }

    /** 关闭会员属性
     * @param int $id 属性id
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfoOff($id = 0)
    {
        $attr = MUserAttr::find($id);
        if (empty($attr)) {
            $this->data = $this->makeJsCode(1, '该用户不存在');
            return back()->with($this->data);
        }
        if ($attr->editAttrSave()) {
            $this->data = $this->makeJsCode(0, "会员属性关闭成功！");
            MLog::log("关闭了会员属性为 $attr->name 的信息");
        } else {
            $this->data = $this->makeJsCode(0, "会员属性关闭失败！");
        }
        return back()->with($this->data);
    }

    /** 开启会员属性
     * @param int $id 属性id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function userInfoOn($id = 0)
    {
        $attr = MUserAttr::find($id);
        if (empty($attr)) {
            $this->data = $this->makeJsCode(1, '该用户不存在');
            return back()->with($this->data);
        }
        if ($attr->onAttrSave()) {
            $this->data = $this->makeJsCode(0, "会员属性开启成功！");
            MLog::log("开启了会员属性为 $attr->name 的信息");
        } else {
            $this->data = $this->makeJsCode(0, "会员属性开启失败！");
        }
        return back()->with($this->data);
    }

    /** 删除会员信息属性
     * @param int $id 信息id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function userInfoDel($id = 0)
    {
        $attr = MUserAttr::find($id);
        if (empty($attr)) {
            $this->data = $this->makeJsCode(1, '该属性不存在');
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use ($attr) {
                if ($attr->UserInfoDel()) {
                    $this->data = $this->makeJsCode(0, "会员属性删除成功！");
                    MLog::log("删除了会员属性为 $attr->name 的信息");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "删除失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "删除失败！");
        }

        return back()->with($this->data);
    }

    /**
     * 后台申请报单中心界面
     */
    public function applyBdzxPage(Request $request, $flag, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.apply.bdzx', ['flag' => $flag]), 15, $request->getQueryString());
        $query = (new MBdzxLog())->query();

        if ($flag == 0) {//申请中
            $query = MBdzxLog::where('status', MBdzxLog::bdzx_sh_apply);
        } else if ($flag == 1) {
            $query = MBdzxLog::where('status', MBdzxLog::bdzx_sh_yes);
        } else if ($flag == 2) {
            $query = MBdzxLog::where('status', MBdzxLog::bdzx_sh_no);
        }

        //指定了按时间段搜索
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按会员用户名搜索
                $query = $query->where('username', 'like', "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) { //按申请唯一编号搜索
                $query = $query->where('no', $request->search_str);

            } elseif ($request->search_type == 3) { //按会员ID搜索
                $query = $query->where('uid', $request->search_str);

            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['userlogs'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('time', 'desc')
            ->get();

        $this->fyViewInit($this->data);

        $this->data['flag'] = $flag;
        return view('admin.bdzx')->with($this->data);
    }

    /**
     * 允许成为报单中心
     * $id 申请报单中心用户
     */
    public function allowBdzx(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的处理结果，以便用户查看！");
            return back()->with($this->data);
        }
        $bdzxlog = MBdzxLog::where('id', $request->id)->first();
        $user = MUser::find($bdzxlog->uid);

        if (empty($bdzxlog)) {
            $this->data = $this->makeJsCode(1, "申请报单中心无效！");
            return back()->with($this->data);
        }

        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "该用户不存在！");
            return back()->with($this->data);
        }

        if ($user->bdzx_status == 1 || $user->bdzx_status == 0) {
            $this->data = $this->makeJsCode(1, "该用户已为报单中心或未申请不能再次通过审核！");
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use (&$request, $bdzxlog, $user) {
                if ($user->throwBdzx() && $bdzxlog->allow($request->text)) {
                    MLog::log("同意了会员 $user->username 的报单申请中心");
                    $this->data = $this->makeJsCode(0, "操作成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败! ");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
        }

        return back()->with($this->data);
    }

    /**
     *  拒绝申请报单中心
     */
    public function denyBdzx(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的拒绝申请理由！");
            return back()->with($this->data);
        }

        $bdzxlog = MBdzxLog::where('id', $request->id)->first();
        $user = MUser::find($bdzxlog->uid);

        if (empty($bdzxlog)) {
            $this->data = $this->makeJsCode(1, "报单申请单无效！");
            return back()->with($this->data);
        }

        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "该用户不存在！");
            return back()->with($this->data);
        }

        if ($user->bdzx_status == 1 || $user->bdzx_status == 0) {
            $this->data = $this->makeJsCode(1, "该用户已为报单中心或未申请不能拒绝！");
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use (&$request, &$bdzxlog, $user) {
                if ($user->closeBdzx($bdzxlog) && $bdzxlog->deny($request->text)) {
                    MLog::log("拒绝了会员 $user->username 的报单申请中心");
                    $this->data = $this->makeJsCode(0, "拒绝申请报单中心成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
        }
        return back()->with($this->data);
    }

}